package com.antipov.odp.server;

import java.io.IOException;
import java.net.*;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Andrew Antipov
 * Date: 18.02.14
 * Time: 23:05
 */
public class Server {
	private static final int PORT = 5051;

	public static void main(String[] args) throws IOException {
		InetAddress ip = getIPAddress(true);
		ServerSocket serverSocket = new ServerSocket(PORT, 50, InetAddress.getLocalHost());
		System.out.println("Socket started");
		while (true) {
			Socket socket = serverSocket.accept();
			Handler handler = new Handler(socket);
			try {
				handler.start();
			} catch (Exception e) {
				socket.close();
			}
		}
	}

	public static InetAddress getIPAddress(boolean useIPv4) {
		try {
			List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
				for (InetAddress addr : addrs) {
					if (!addr.isLoopbackAddress()) {
						String sAddr = addr.getHostAddress().toUpperCase();
						boolean isIPv4 = true;
						if (useIPv4) {
							if (addr instanceof Inet4Address)
								return addr;
						}
					}
				}
			}
		} catch (Exception ex) { } // for now eat exceptions
		return null;
	}
}
